package ferp.android.tasks.center;

import android.content.Context;
import android.os.AsyncTask;
import ferp.android.activities.preferences.Preferences;
import ferp.center.client.Action;
import ferp.center.network.RequestProfileCreate;
import ferp.center.network.ResponseProfileCreate;
import ferp.core.log.Log;
import ferp.core.player.Profile;

/**
 * User: igorgok
 * Date: 5/20/12 12:56 PM
 */
public class TaskProfileCreate extends AsyncTask<Void, Void, Void>
{
  public interface Listener
  {
    void onBeforeProfileCreation();
    void onAfterProfileCreation();
  }

  public TaskProfileCreate(Context context, Profile profile, Listener listener)
  {
    this.context = context;
    this.profile = profile;
    this.listener = listener;
  }

  @Override
  protected void onPreExecute()
  {
    listener.onBeforeProfileCreation();
  }

  @Override
  protected Void doInBackground(Void... voids)
  {
    try
    {
      if (profile.useCenter)
      {
        RequestProfileCreate request = new RequestProfileCreate();

        request.id = profile.centerId;
        request.phone = Preferences.getDeviceID(context);
        request.name = profile.nickname;
        request.locale = profile.settings.locale.code();
        request.poolBalance = 0; // profile.balance;
        request.lastPlayedPoolSize = profile.settings.poolSize;

        ResponseProfileCreate response = Action.execute(profile.centerId == 0 ? Action.PROFILE_CREATE : Action.PROFILE_UPDATE, request, ResponseProfileCreate.class);

        profile.centerId = response.id;
      }
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return null;
  }

  @Override
  protected void onPostExecute(Void aVoid)
  {
    listener.onAfterProfileCreation();
  }

  private final Context context;
  private final Profile profile;
  private final TaskProfileCreate.Listener listener;
}
